package testschedul;

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-11-26
 * Time:15:53
 */
public class TestDemo {
    public static int getMatTime(int[] taskTime,int m){
        int n = taskTime.length;
        Arrays.sort(taskTime);//默认为升序
        int[] machines = new int[m];
        if ( n < m){
            return taskTime[n -1];
        }else {

            for (int i = n -1; i >= 0; i--) {
                int index = 0;
                int machineTime = machines[index];
                for (int j = 1; j < m; j++) {
                    if (machineTime > machines[j]){
                        index = j;
                        machineTime = machines[j];
                    }
                }
                machines[index] += taskTime[i];
            }
            return  findmax(machines);
        }
    }

    private static int findmax(int[] machines) {
        int max = machines[0];
        for (int i = 1; i < machines.length; i++) {
            if (machines[i] > max){
                max = machines[i];
            }
        }
        return  max;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n,m;
        System.out.println("请输入任务个数个机器个数");
        n = scanner.nextInt();
        m = scanner.nextInt();
        System.out.println("请输入任务的时间");
        int[] taskTime = new int[n];
        for (int i = 0; i < n; i++) {
            taskTime[i] = scanner.nextInt();
        }
        int ret = getMatTime(taskTime,m);
        System.out.println("最小任务时长是:" + ret);
    }
}
